package com.ccteam.admin.view.fragments.banner

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.Glide
import com.ccteam.admin.R
import com.ccteam.admin.REFRESH_REQUEST_KEY
import com.ccteam.admin.core.EDIT_TYPE
import com.ccteam.admin.databinding.FragmentBannerDetailBinding
import com.ccteam.admin.utils.EventObserver
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.view.bean.SelectInfoResult
import com.ccteam.admin.view.bean.UploadResult
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_ALBUM
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_ARTIST
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_REQUEST_KEY
import com.ccteam.admin.view.fragments.common.SelectFragment.Companion.SELECT_RESULT
import com.ccteam.admin.view.fragments.common.UploadFragment
import com.ccteam.admin.viewmodels.banner.BannerDetailViewModel
import com.ccteam.model.banner.BANNER_TYPE_ALBUM
import com.ccteam.model.banner.BANNER_TYPE_ARTIST
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/3/26
 */
@AndroidEntryPoint
class BannerDetailFragment: Fragment() {

    private var _binding: FragmentBannerDetailBinding? = null
    private val binding get() = _binding!!

    private val bannerDetailViewModel by viewModels<BannerDetailViewModel>()

    private val args by navArgs<BannerDetailFragmentArgs>()

    private val typeItems = arrayOf("专辑","歌手")

    /**
     * 选择图片的内容
     * 选择完手机中的图片后，将其存储到ViewModel中并进行对应UI更新
     */
    private val selectImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let {
            bannerDetailViewModel.setBannerUrl(it.toString())
            bannerDetailViewModel.updateBannerEditInfo()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setFragmentResultListener(SELECT_REQUEST_KEY){ _, bundle ->
            val selectResult = bundle.getParcelable<SelectInfoResult>(SELECT_RESULT)
            selectResult?.let {
                bannerDetailViewModel.setBannerIdSuccess(true)
                bannerDetailViewModel.setBannerItemId(it)
            }
        }

        setFragmentResultListener(UploadFragment.UPLOAD_REQUEST_KEY) { _, bundle ->
            bundle.getParcelable<UploadResult>(UploadFragment.UPLOAD_URL_RESULT)?.let { result ->
                bannerDetailViewModel.setBannerUrl(result.url)
                bannerDetailViewModel.setUrlSuccess(true)
                bannerDetailViewModel.updateBannerEditInfo()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentBannerDetailBinding.inflate(inflater,container,false)
        binding.btnDelete.isVisible = args.bannerEditType == EDIT_TYPE
        if(args.bannerEditType == EDIT_TYPE){
            binding.btnEdit.setIconResource(R.drawable.ic_edit)
            binding.btnEdit.text = getString(R.string.description_confirm_edit)
        } else {
            binding.btnEdit.setIconResource(R.drawable.ic_add)
            binding.btnEdit.text = getString(R.string.description_banner_edit_add)
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        bannerDetailViewModel.bannerInfo.observe(viewLifecycleOwner, {
            updateUI(it)
        })

        bannerDetailViewModel.editButtonEnable.observe(viewLifecycleOwner, {
            binding.btnEdit.isEnabled = it
        })
        bannerDetailViewModel.deleteButtonEnable.observe(viewLifecycleOwner, {
            binding.btnDelete.isEnabled = it
        })

        bannerDetailViewModel.itemSubtitle.observe(viewLifecycleOwner, {
            binding.tvSelectItemInfo.text = it
        })

        bannerDetailViewModel.itemTypeSuccess.observe(viewLifecycleOwner, {
            binding.btnSelectId.isEnabled = it
        })

        bannerDetailViewModel.loadMessage.observe(viewLifecycleOwner, {

            binding.containerBannerEdit.isVisible = it is LoadMessage.NotLoading

            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

        bannerDetailViewModel.editLoadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnEdit.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Error){
                Snackbar.make(
                    binding.root,
                    it.errorMessage.description ?: "未知错误",
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
            } else if(it is LoadMessage.Success) {
                Snackbar.make(
                    binding.root,
                    getString(R.string.description_success),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
                setFragmentResult(REFRESH_REQUEST_KEY, bundleOf(REFRESH_REQUEST_KEY to true))
                findNavController().navigateUp()
            }
        })

        bannerDetailViewModel.deleteLoadMessage.observe(viewLifecycleOwner,EventObserver{
            binding.btnDelete.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Error){
                Snackbar.make(
                    binding.root,
                    it.errorMessage.description ?: "未知错误",
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
            } else if(it is LoadMessage.Success) {
                Snackbar.make(
                    binding.root,
                    getString(R.string.description_success),
                    Snackbar.LENGTH_SHORT
                ).setAnchorView(binding.btnEdit).show()
                setFragmentResult(REFRESH_REQUEST_KEY, bundleOf(REFRESH_REQUEST_KEY to true))
                findNavController().navigateUp()
            }
        })

        binding.editBannerUrl.addOnEditTextAttachedListener { inputLayout ->
            inputLayout.editText?.doOnTextChanged { text, _, _, _ ->
                bannerDetailViewModel.setBannerUrl(text.toString())
                bannerDetailViewModel.setUrlSuccess(text.toString().isNotEmpty())
            }
        }

        binding.statusView.setRetryClickListener {
            bannerDetailViewModel.refreshBannerInfo()
        }

        binding.containerSelectType.setOnClickListener {
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(resources.getString(R.string.description_banner_type))
                .setNeutralButton(resources.getString(R.string.description_cancel)) { dialog, which ->

                }
                .setPositiveButton(resources.getString(R.string.description_confirm)) { dialog, which ->
                }
                .setSingleChoiceItems(typeItems, bannerDetailViewModel.bannerInfo.value?.type ?: -1) { dialog, which ->
                    bannerDetailViewModel.setBannerType(which)
                    bannerDetailViewModel.setBannerTypeSuccess(true)
                    bannerDetailViewModel.setBannerIdSuccess(false)
                    bannerDetailViewModel.setBannerItemId(null)
                }
                .show()
        }

        binding.btnSelectId.setOnClickListener {
            val type = if(bannerDetailViewModel.bannerInfo.value?.type == BANNER_TYPE_ARTIST){
                SELECT_ARTIST
            } else {
                SELECT_ALBUM
            }
            findNavController().navigate(BannerDetailFragmentDirections
                .actionBannerDetailFragmentToSelectFragment(type))
        }

        binding.btnUpload.setOnClickListener {
            selectImage.launch("image/*")
        }

        binding.btnEdit.setOnClickListener {
            bannerDetailViewModel.editOrAddBannerInfo()
        }

        binding.btnDelete.setOnClickListener {
            bannerDetailViewModel.deleteBannerInfo()
        }
    }

    private fun updateUI(bannerInfo: BannerDetailViewModel.BannerEditInfo) = with(binding){
        editBannerId.editText?.setText(bannerInfo.id)
        Glide.with(ivBanner)
            .load(bannerInfo.url)
            .placeholder(R.drawable.img_default_album_big)
            .into(ivBanner)
        editBannerUrl.editText?.setText(bannerInfo.url)

        if(bannerInfo.type == BANNER_TYPE_ALBUM){
            tvSelectType.text = requireContext().getString(R.string.description_album)
        } else if(bannerInfo.type == BANNER_TYPE_ARTIST){
            tvSelectType.text = requireContext().getString(R.string.description_artist)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        binding.editBannerUrl.clearOnEditTextAttachedListeners()

        _binding = null
    }
}